package com.example.newsdaily.slice;

import com.alibaba.fastjson.JSON;
import com.example.newsdaily.*;
import com.example.newsdaily.adapter.CommonProvider;
import com.example.newsdaily.adapter.ViewHolder;
import com.example.newsdaily.entity.ItemImage;
import com.example.newsdaily.entity.TBriefNews;
import com.example.newsdaily.entity.TCollection;
import com.example.newsdaily.provider.NavigationPageProvider;
import com.example.newsdaily.provider.SwiperPageProvider;
import com.example.newsdaily.utl.ContainUtil;
import com.example.newsdaily.utl.HttpClientUtil;
import com.example.newsdaily.utl.LocalDataUtil;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.ability.LifecycleObserver;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.agp.colors.RgbColor;
import ohos.agp.components.*;
import ohos.agp.components.element.PixelMapElement;
import ohos.agp.components.element.ShapeElement;
import ohos.data.preferences.Preferences;
import ohos.global.resource.NotExistException;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

public class MainAbilitySlice extends AbilitySlice {
    boolean flag = true;

    // 页面切换变量声明
    PageSlider pageSlider;
    NavigationPageProvider navigationPageProvider;
    TabList tabList;
    TabList.Tab discoverTab, collectionTab, myTab;

    // collection页面变量声明
    public static TCollection tCollection;
    static List<TCollection> collectionList = new ArrayList<>();
    public static ListContainer collectionListContainer;
    public static CommonProvider<TCollection> collectionCommonProvider;

    // discover页面变量声明
    Text pageTitle;
    Timer timer;
    int currentPage = 0;
    static final int SWITCH_INTERVAL = 3000;
    PageSlider swiperSlider;
    List<TBriefNews> tBriefNewsList = new ArrayList<>();
    ListContainer discoverListContainer;
    CommonProvider<TBriefNews> discoverCommonProvider;

    // user页面变量声明
    Preferences preferences= LocalDataUtil.preferences;
    Button exitlog;
    Button changecode;
    Button developers;
    String user_name=LocalDataUtil.preferences.getString(ContainUtil.USER_NAME_KEY,"");
    Text name;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);

        initNavigation();

        // 监听TabLis组件
        tabList.addTabSelectedListener(new TabList.TabSelectedListener() {
            @Override
            public void onSelected(TabList.Tab tab) {
                int position = tab.getPosition();
                pageSlider.setCurrentPage(position);

                if (position == 0) {
                    initDiscoverPage();
                } else if (position == 1) {
                    initCollectionPage();
                } else {
                    initUserPage();
                }

                if (tab == discoverTab) {
                    setTabImage(tab, ResourceTable.Media_icon_news_selected);
                } else if (tab == collectionTab) {
                    setTabImage(tab, ResourceTable.Media_icon_collections_selected);
                } else {
                    setTabImage(tab, ResourceTable.Media_icon_my_selected);
                }


            }
            @Override
            public void onUnselected(TabList.Tab tab) {
                if (tab == discoverTab) {
                    setTabImage(tab, ResourceTable.Media_icon_news_unselected);
                } else if (tab == collectionTab) {
                    setTabImage(tab, ResourceTable.Media_icon_collections_unselected);
                } else {
                    setTabImage(tab, ResourceTable.Media_icon_my_unselected);
                }
            }
            @Override
            public void onReselected(TabList.Tab tab) {}
        });
        tabList.selectTabAt(0);

        // 监听pageSlider切换
        pageSlider.addPageChangedListener(new PageSlider.PageChangedListener() {
            @Override
            public void onPageSliding(int i, float v, int i1) {}
            @Override
            public void onPageSlideStateChanged(int i) {}
            @Override
            public void onPageChosen(int i) {
                if(i != tabList.getSelectedTabIndex()) {
                    tabList.selectTabAt(i);
                }
            }
        });
    }

    private void initUserPage() {
        exitlog=(Button)findComponentById(ResourceTable.Id_exit_lg);
        changecode=(Button)findComponentById(ResourceTable.Id_user_rstps);
        developers=(Button)findComponentById(ResourceTable.Id_user_developer);
        name=(Text)findComponentById(ResourceTable.Id_user_name);
        name.setText(user_name);

        exitlog.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                preferences.putBoolean(ContainUtil.USER_REMEMBER_KEY,false);
                Intent intent1=new Intent();
                Operation operation=new Intent.OperationBuilder()
                        .withBundleName(getBundleName())
                        .withAbilityName(LoginAbility.class)
                        .build();
                intent1.setOperation(operation);
                startAbility(intent1);
            }
        });

        changecode.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                Intent intent=new Intent();
                Operation operation=new Intent.OperationBuilder()
                        .withBundleName(getBundleName())
                        .withAbilityName(ChangeCodeAbility.class)
                        .build();
                intent.setOperation(operation);
                startAbility(intent);
            }
        });

        developers.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                Intent intent=new Intent();
                Operation operation=new Intent.OperationBuilder()
                        .withBundleName(getBundleName())
                        .withAbilityName(DeveloperAbility.class)
                        .build();
                intent.setOperation(operation);
                startAbility(intent);
            }
        });
    }

    private void initDiscoverPage() {
        // discover页面动态显示
        swiperSlider = (PageSlider) findComponentById(ResourceTable.Id_page_slider);
        List<ItemImage> list = getDataSwiper();
        SwiperPageProvider pageProvider = new SwiperPageProvider(list,this);
        swiperSlider.setProvider(pageProvider);

        PageSliderIndicator indicator = (PageSliderIndicator)findComponentById(ResourceTable.Id_indicator);
        ShapeElement normalElement = new ShapeElement();
        normalElement.setRgbColor(RgbColor.fromArgbInt(0x808080));
        normalElement.setAlpha(250);
        normalElement.setShape(ShapeElement.RECTANGLE);
        normalElement.setBounds(0, 0, 16, 16);
        ShapeElement selectedElement = new ShapeElement();
        selectedElement.setRgbColor(RgbColor.fromArgbInt(0x242424));
        selectedElement.setAlpha(250);
        selectedElement.setShape(ShapeElement.RECTANGLE);
        selectedElement.setBounds(0, 0, 24, 24);
        indicator.setItemElement(normalElement, selectedElement);
        indicator.setItemOffset(60);
        indicator.setPageSlider(swiperSlider);

        List<String> listTitle = getTitle();
        pageTitle = (Text) findComponentById(ResourceTable.Id_page_slider_title);

        if(flag) {
            flag = false;
            timer = new Timer();
            startAutoSwitch();
        }

        swiperSlider.addPageChangedListener(new PageSlider.PageChangedListener() {
            @Override
            public void onPageSliding(int i, float v, int i1) {}
            @Override
            public void onPageSlideStateChanged(int i) {}
            @Override
            public void onPageChosen(int i) {
                pageTitle.setText(listTitle.get(i));
                currentPage = i;
            }
        });

        discoverListContainer = (ListContainer) findComponentById(ResourceTable.Id_other_news);

        updateDiscover();

        discoverListContainer.setItemSelectedListener((listContainer, component, i, l) -> {
            Intent intent1 = new Intent();
            Operation operation = new Intent.OperationBuilder()
                    .withBundleName("com.example.newsdaily")
                    .withAbilityName("com.example.newsdaily.NewsDetailAbility")
                    .build();
            intent1.setOperation(operation);
            intent1.setParam("newsid", (long) tBriefNewsList.get(i).getId());
            startAbility(intent1);
        });

        findComponentById(ResourceTable.Id_page_slider).setClickedListener(
                component -> {
                    Intent intent3 = new Intent();
                    Operation operation = new Intent.OperationBuilder()
                            .withBundleName("com.example.newsdaily")
                            .withAbilityName("com.example.newsdaily.NewsDetailAbility")
                            .build();
                    intent3.setOperation(operation);
                    intent3.setParam("newsid", (long) currentPage + 3);
                    intent3.setParam("ter", false);
                    startAbility(intent3);
                }
        );
    }

    private void initCollectionPage() {
        // collection页面的动态显示
        collectionListContainer = (ListContainer) findComponentById(ResourceTable.Id_collection_news);
        updateCollection();

        collectionListContainer.setItemSelectedListener((listContainer1, component, i, l) -> {
            Intent intent2 = new Intent();
            Operation operation = new Intent.OperationBuilder()
                    .withBundleName("com.example.newsdaily")
                    .withAbilityName("com.example.newsdaily.NewsDetailAbility")
                    .build();
            intent2.setOperation(operation);
            intent2.setParam("newsid", (long) collectionList.get(i).gettBriefNews().getId());
            intent2.setParam("ter", true);
            startAbility(intent2);
            getLifecycle().addObserver(new LifecycleObserver() {
                @Override
                public void onForeground(Intent intent) {
                    getLifecycle().removeObserver(this);
                    updateCollection();
                }
            });
        });
    }

    private void initNavigation() {
        // 初始化pageSlider
        pageSlider = (PageSlider) findComponentById(ResourceTable.Id_navigation_bar);
        List<Integer> ids = getData();
        navigationPageProvider = new NavigationPageProvider(ids, this);
        pageSlider.setProvider(navigationPageProvider);

        // 初始化TabList
        tabList = (TabList) findComponentById(ResourceTable.Id_tab_list);
        tabList.setFixedMode(true);

        // 图标Tab初始化
        discoverTab = tabList.new Tab(getContext());
        setTabImage(discoverTab, ResourceTable.Media_icon_news_unselected);
        tabList.addTab(discoverTab);

        collectionTab = tabList.new Tab(getContext());
        setTabImage(collectionTab, ResourceTable.Media_icon_collections_unselected);
        tabList.addTab(collectionTab);

        myTab = tabList.new Tab(getContext());
        setTabImage(myTab, ResourceTable.Media_icon_my_unselected);
        tabList.addTab(myTab);
    }

    private void updateDiscover() {
        new Thread(
                new Runnable() {
                    @Override
                    public void run() {
                        // 从数据库中得到所有新闻
                        String result = HttpClientUtil.doGet(ContainUtil.FIND_BRIEF_NEWS);
                        tBriefNewsList = JSON.parseArray(result, TBriefNews.class);
                        getUITaskDispatcher().asyncDispatch(new Runnable() {
                            @Override
                            public void run() {

                                discoverCommonProvider = new CommonProvider<TBriefNews>(tBriefNewsList, getContext(), ResourceTable.Layout_other_news_item) {
                                    @Override
                                    protected void convert(ViewHolder holder, TBriefNews item, int position) {
                                        holder.setImageResource(ResourceTable.Id_other_image, ContainUtil.detail_pic_id[item.getPicId()]);
                                        holder.setText(ResourceTable.Id_other_title, item.getTitle());
                                        holder.setText(ResourceTable.Id_other_content, item.getContent());
                                        holder.setText(ResourceTable.Id_other_publisher, item.getPublisher());
                                    }
                                };
                                discoverListContainer.setItemProvider(discoverCommonProvider);
                            }
                        });
                    }
                }
        ).start();
    }

    private void startAutoSwitch() {
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                getUITaskDispatcher().asyncDispatch(()->{
                    currentPage = (currentPage+1)%5;
                    swiperSlider.setCurrentPage(currentPage);
                });
            }
        },0,SWITCH_INTERVAL);
    }

    private List<String> getTitle() {
        List<String> list = new ArrayList<>();
        list.add(new String("丝路电商班列（西安—乌鲁木齐）开行突破100列"));
        list.add(new String("甘肃肃南：夏日祁连山国家公园景色迷人"));
        list.add(new String("投资天津丨镜头直击“七彩码头”之美"));
        list.add(new String("新疆布尔津迎来旅游旺季"));
        list.add(new String("2024全球数字经济大会开幕"));

        return list;
    }

    private List<ItemImage> getDataSwiper() {
        List<ItemImage> list = new ArrayList<>();
        list.add(new ItemImage(ResourceTable.Media_swiper01));
        list.add(new ItemImage(ResourceTable.Media_swiper02));
        list.add(new ItemImage(ResourceTable.Media_swiper03));
        list.add(new ItemImage(ResourceTable.Media_swiper04));
        list.add(new ItemImage(ResourceTable.Media_swiper05));
        return list;
    }

    private void updateCollection() {
        new Thread(
                new Runnable() {
                    @Override
                    public void run() {
                        String result = HttpClientUtil.doGet(ContainUtil.FIND_COLLECTION_BY_USER+"?TUser="+ MyApplication.tuser.getId());
                        collectionList = JSON.parseArray(result, TCollection.class);
                        getUITaskDispatcher().asyncDispatch(new Runnable() {
                            @Override
                            public void run() {
                                collectionCommonProvider = new CommonProvider<TCollection>(collectionList, getContext(), ResourceTable.Layout_collection_news_item) {
                                    @Override
                                    protected void convert(ViewHolder holder, TCollection item, int position) {
                                        holder.setImageResource(ResourceTable.Id_collection_image, ContainUtil.detail_pic_id[item.gettBriefNews().getPicId()]);
                                        holder.setText(ResourceTable.Id_collection_title, item.gettBriefNews().getTitle());
                                        holder.setText(ResourceTable.Id_collection_content, item.gettBriefNews().getContent());
                                        holder.setText(ResourceTable.Id_collection_publisher, item.gettBriefNews().getPublisher());
                                        Button deleteButton = holder.getView(ResourceTable.Id_collection_delete_btn);

                                        holder.getView(ResourceTable.Id_collection_delete_btn).setClickedListener(component -> {
                                            collectionList.remove(item);
                                            collectionListContainer.getItemProvider().notifyDataChanged();
                                            new Thread(
                                                    new Runnable() {
                                                        @Override
                                                        public void run() {
                                                            HttpClientUtil.doGet(ContainUtil.DELETE_COLLECTION_NEW+"?id="+item.getId());
                                                        }
                                                    }
                                            ).start();
                                        });
                                    }
                                };
                                collectionListContainer.setItemProvider(collectionCommonProvider);
                            }
                        });
                    }
                }
        ).start();
    }

    private List<Integer> getData() {
        List<Integer> list = new ArrayList<>();
        list.add(ResourceTable.Layout_ability_discover);
        list.add(ResourceTable.Layout_ability_collection);
        list.add(ResourceTable.Layout_ability_User);

        return list;
    }

    void setTabImage(TabList.Tab tab, int imgId) {
        try{
            tab.setIconElement(new PixelMapElement(getResourceManager().getResource(imgId)));
        } catch (IOException e) {
            e.printStackTrace();
        } catch (NotExistException e) {
            e.printStackTrace();
        }
    }


    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (timer != null) {
            timer.cancel();
            timer=null;
        }
    }
}
